package com.example.service.impl;

import ch.qos.logback.classic.Logger;
import com.example.entity.UserRegId;
import com.example.mapp.UserRegIdMapp;
import com.example.service.UserRegIdService;
import com.example.util.JpushUtil;
import com.example.util.ResultUtil;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by douyx on 2017/11/14.
 */
@Service
@PropertySource({"classpath:application.properties"})
public class UserRegIdServiceImpl implements UserRegIdService {

	private final static Logger logger = (Logger) LoggerFactory.getLogger(UserRegIdServiceImpl.class);

	@Autowired
	UserRegIdMapp userRegIdMapp;

	@Value("${jpush.appkey}")
	private String appkey;

	@Value("${jpush.masterSecret}")
	private String masterSecret;

	@Override
	public Map<String, Object> add(UserRegId userRegId) {
		try {
			UserRegId userRegIdOld = userRegIdMapp.findById(userRegId.getUserId());
			//更新的时候要看一下设备号变了没
			if (null != userRegIdOld && userRegIdOld.getId() != null) {

				//新设备替换老设备，通知老设备被踢了
				if(!userRegId.getRegisterId().equals(userRegIdOld.getRegisterId())){
					String content = "您已经在别的设备登录";
					String title = "被踢了";
					JpushUtil js = new JpushUtil(appkey, masterSecret, content, title);
					List<String> deviceIds = new ArrayList<>();
					if(null!=userRegIdOld.getRegisterId()){
						deviceIds.add(userRegIdOld.getRegisterId());
						js.sendPushAll(true, deviceIds);
					}
					userRegIdOld.setRegisterId(userRegId.getRegisterId());
					userRegIdMapp.update(userRegIdOld);
				}
			} else {
				userRegIdMapp.insert(userRegId);
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
			return ResultUtil.returnError("提交失败" + e.getMessage(), null);
		}
		return ResultUtil.returnSuccess("提交成功", null);
	}
}
